# -*- coding: utf-8 -*-
"""
lottery信息
"""
import json
import logging

from django.utils.encoding import smart_unicode
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.decorators.http import require_GET, require_POST

from common.lottery import admin as db
from common.lottery.cyclical.abstract.order import manual_cancel_orders

from common.utils import tz
from common.utils.decorator import response_wrapper
from common.utils.api import token_required, check_params

_LOGGER = logging.getLogger(__name__)


class ActivityView(TemplateView):

    def get(self, req, activity_type):
        query_dct = req.GET.dict()
        items, total_count = db.list_activity(int(activity_type), query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            for k in ('start_ts', 'announce_ts', 'end_ts'):
                if k in data and data[k]:
                    data[k] = tz.ts_to_local_date_str(data[k], f='%Y-%m-%d %H:%M:%S')
            data['activity_type'] = int(activity_type)
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(ActivityView, self).dispatch(*args, **kwargs)


class ActivityOrderView(TemplateView):

    def get(self, req, activity_type):
        query_dct = req.GET.dict()
        items, total_count = db.list_order(int(activity_type), query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            data['activity_type'] = int(activity_type)
            if 'track_id' in data:
                data['track_id'] = str(data['track_id'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(ActivityOrderView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def refund_orders(req, activity_type):
    parmas_dct = json.loads(req.body)
    check_params(parmas_dct, ('ids',))
    order_ids = parmas_dct['ids']
    succ_list, fail_list = manual_cancel_orders(int(activity_type), order_ids)
    return {
        'succ_list': succ_list
    }


@require_POST
@response_wrapper
@token_required
def fresh_order(req, activity_type, order_id):
    from common.lottery.cyclical.model import ACTIVITY_MODEL, ORDER_LOGIC, ORDER_MODEL
    from common.lottery.cyclical.abstract.order import WinOrderApplyer
    activity_type = int(activity_type)
    order_id = int(order_id)
    ac_table = ACTIVITY_MODEL[activity_type]
    order_table = ORDER_MODEL[activity_type]
    order = order_table.query.filter(order_table.id == order_id).first()
    term = order.term
    logic = ORDER_LOGIC[activity_type]
    ac = ac_table.query.filter(ac_table.term == term).one()
    if ac.status != 3:
        return {'message': 'term not announce yet'}
    applyer = WinOrderApplyer(term, ac.number, logic, activity_type)
    applyer.apply()
    return {
        'message': 'successfully manual apply winner',
    }
